import Vue from 'vue'
import Vuex from 'vuex'
import axios from 'axios'

Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    // 所有的任务列表，包括ID，info，done
    list: [],
    // 输入框里的值
    inputValue: 'aaa',
    nextId: 5,
    btnKey: 'all'
  },
  mutations: {
    //  axios 异步请求拿到 list.json里的数据后，action里commit传递的data给 initList 来初始化list
    initList (state, list) {
      state.list = list
    },
    // 为 store 中的inputValue 赋值
    setInputValue (state, value) {
      state.inputValue = value
    },
    addItem (state, inputValue) {
      const newList = {
        id: state.nextId,
        info: inputValue,
        done: false
      }
      state.list.push(newList)
      state.nextId++
      state.inputValue = ''
    },
    removeItemById (state, id) {
      // 根据ID查找对应的索引
      const i = state.list.findIndex(x => x.id === id)
      // 根据索引，删除对应的元素
      if (i !== -1) {
        state.list.splice(i, 1)
      }
    },
    // 修改列表项的选中状态
    statusChange (state, param) {
      const i = state.list.findIndex(x => x.id === param.id)
      // 根据索引，查找对应的元素
      if (i !== -1) {
        state.list[i].done = param.status
      }
    },
    clearDone (state) {
      state.list = state.list.filter(x => x.done === false)
    },
    changeBtnVal (state, val) {
      state.btnKey = val
    }
  },
  actions: {
    getList (context) {
      axios.get('/list.json').then(({ data }) => {
        console.log(data)
        context.commit('initList', data)
      })
    }
  },
  getters: {
    // 统计未完成的任务的条数
    unDoneLength (state) {
      return state.list.filter(x => x.done === false).length
    },
    infoList (state) {
      if (state.btnKey === 'all') {
        return state.list
      } else if (state.btnKey === 'undone') {
        return state.list.filter(x => !x.done)
      } else {
        return state.list.filter(x => x.done)
      }
    }
  },
  modules: {
  }
})
